<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;

use App\Models\Order;
use App\Models\PromoterLevel;
use App\Models\Qrcode;
use App\Models\User;
use App\Models\UserExtract;
use App\Models\UserLevel;
use App\Traits\Controllers\AdminTraits;
use App\Transformers\User\UserInfoTransformer;
use App\Transformers\User\UserPromoterTransformer;
use App\Transformers\User\UserTransformer;

use Dingo\Api\Http\Response;
use EasyWeChat\Work\Application;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Symfony\Component\HttpFoundation\StreamedResponse;
use function DI\get;
use function EasyWeChat\Kernel\Support\get_client_ip;
use function PHPUnit\Framework\returnArgument;


class PromoterController extends Controller
{

    use AdminTraits;

    public $model = User::class;

    public $transformer = UserTransformer::class;


    /**
     *分销头部数据
     */

    public function Ispromoter(Request $request)
    {
        //分销人员数量
        $count = $this->getQuery()
            ->pimp()->where('is_promoter', 1)
            ->count();



        $ids = $this->getQuery()
                ->pimp()
                ->where('is_promoter', 1)
                ->where('is_extension', 1)
                ->pluck('id');

        //发展会员人数
        $promoter_count = $this->getQuery()
            ->pimp()
            ->whereIn('promoter_id', $ids)
            ->count();

        //订单总数量
        $order_count = Order::query()->pimp()
            ->where('paid', 1)
            ->whereIn('user_id', $ids)
            ->count();

        //订单总价钱
        $order_amount_sum = Order::query()
            ->pimp()
            ->where('paid', 1)
            ->whereIn('promoter_id', $ids)
            ->sum('total_price');

        //提现次数
        $extract_count = UserExtract::query()
            ->where('status', 'withdrawncash')
            ->whereIn('user_id', $ids)
            ->pimp()
            ->count();

        //未提现金额
        $has_amount = UserExtract::query()
            ->where('status', 'underreview')
            ->whereIn('user_id', $ids)
            ->sum('balance');


        $data = [
            [
                'name' => '分销人员数量',
                'promoter_count' => $count,
            ],
            [
                'name' => '发展会员人数',
                'is_promoter' => $promoter_count
            ],
            [
                'name' => '订单数量',
                'orders' => $order_count
            ],
            [
                'name' => '订单金额',
                'order_price' => $order_amount_sum

            ],

            [
                'name' => '提现次数',
                'extract_num' => $extract_count


            ],
            [
                'name' => '未提现金额',
                'has_amount' => $has_amount

            ]


        ];


        return $this->response->array($data);




    }

    /**
     * @return array
     * 分销员列表信息
     */

    public function promoterlist()
    {

        //分销员列表
        $info = $this->getQuery()
            ->pimp()
            //关联订单数量
            ->withCount([
                'promoterOrder' => function (Builder $query) {
                    $query->where('paid', 1);
                }
            ])
            //订单总金额
            ->withSum('order','pay_price')
            //分销员等级
            ->with('PromoterLevel:user_id,level')
            //提现总金额
            ->withSum('userextract','extract_price')
            //未提现金额
            ->withSum('userextract','balance')
            //提现次数
            ->withCount([
                'userextract' => function (Builder $query) {
                    $query->where('status', 'withdrawncash');
                }
            ])
            ->where('is_promoter', 1)
            ->where('is_extension', 1)

            ->paginate($this->getPageLimit());

        return $this->response->paginator($info,new UserInfoTransformer());

    }

    /**
     * 推广人列表
     */


    public function Promoter()
    {
        $ids = $this->getQuery()
            ->where('is_promoter', 1)
            ->pluck('id');
        $info = $this->getQuery()
            ->pimp()
            ->when($ids, function ($query) use ($ids) {
                $query->with([
                    'children' => function ($query) {
                        $query->withCount('order')->with([
                            'children' => function ($query) {
                                $query->withCount('order');
                            }
                        ]);
                    }]);
            })
            ->withCount([
                'order' => function (Builder $query) {
                    $query->where('paid', 1);
                }
            ])
            ->whereIn('promoter_id', $ids)
            ->paginate($this->getPageLimit());


        return $this->response->paginator($info,new UserPromoterTransformer());
    }


    /**
     * 推广人订单
     */
    public function promoterOrder()
    {
        $ids = $this->getQuery()
            ->pimp()
            ->where('is_promoter', 1)
            ->pluck('promoter_id');
        $info = $this->getQuery()
            ->pimp()
            ->when($ids, function ($query) use ($ids) {
                $query->with([
                    'children' => function ($query) {
                        $query->with('order')
                            ->with('children.order');
                    }
                ]);
            })->with('order:id')
            ->whereIn('id', $ids)
            ->get();

        return new Response(compact('info'));
    }

    /**
     * 修改上级推广人
     */
    public function PromoterUpdate(User $user, Request $request)
    {
        $promoter_id = $request->query('promoter_id');

        $request->validate([
            'promoter_id' => 'required',
        ], [
            'promoter_id' => '推荐人不能为空'
        ]);
        //判断所选推荐人是不是自己
        if ($user->id == $promoter_id) {
            return $this->response->errorBadRequest('所选推荐人不能为自己');
        }
        //判断推荐人是不是所选推荐人
        if ($promoter_id == $user->promoter_id) {
            return $this->response->errorBadRequest('当前推荐人已是所选推荐人');
        }

        $user->promoter_id = $request->input('promoter_id');
        $user->save();
        return $this->response->noContent();

    }


    /*
     * 传入一个id返回它上级推广人的信息
     */
    public function getPromoter(User $user){
        $promoterId = $this->getQuery()
             ->where('id',$user->id)
             ->first();

         $promoterInfo = $this->getQuery()
             ->select('nickname','phone',)
             ->where('id',$promoterId->promoter_id)
             ->get()
             ->toArray();
         return $this->response->array($promoterInfo);

    }

    /**
     * 清除上级推广人
     */
    public function EliminatePromoter(User $user)
    {
        //查询推荐人信息
        $info = $this->getQuery()
            ->where('id', $user->promoter_id)
            ->first();
        //解除推荐关系
        $user->promoter_id = Null;
        $user->save();


        return $this->response->noContent();
    }

    /**
     * 取消推广资格
     */
    public function CancelPromoter(User $user)
    {

        $user->is_promoter = 0;

        $user->is_extension = 0;
        $user->save();
        return $this->response->noContent();

    }


    /**
     * 推广方式
     */


    //获取永久二维码
    public function wechatCode(Request $request )
    {
        $userId = $request->input('user_id');
        $qrcode = Qrcode::query()
            ->pimp()
            ->where('user_id', $userId)
            ->first();
        if (empty($qrcode->ticket)) return $this->response->errorBadRequest('获取参数失败');
        return $qrcode->url;




    }

    //小程序二维码

    public function miniCode(Request $request){

       // 获取提交过来的page 页面
//        $param = $this->validate($request,[
//            'page' => 'string|required',
//        ]);
        //验证待效验
        $userInfo = session('userInfo');

        $user_id = $userInfo['user_id'];
        $appId = $userInfo['app_id'];

        //从微信配置中取 app_id , secret
        $res =[
            'app_id'=>config('wechat.mini_program.default.app_id'),
            'secret'=> config('wechat.mini.program.default.secret')
        ];

        //获取配置信息  这里查询数据库 拿到了小程序的appId和secret，根据自己情况而定

        //判断是否拿到 app_id, secret
        if (empty($res)){
            return $this->response->errorBadRequest('获取配置文件失败');
        }



        //配置，具体可以看EasyWeChat 文档
        $config = [
            'app_id'=>$res['app_id'],
            'secret'=>$res['secret'],
            'response_type' => 'array',
        ];
       $app = new Application($config); //初始化 具体看EasyWeChat 文档，有例子
        //设置本地保存地址
        $path = public_path('upload/Qrcode/'); // 本地绝对路径，存放生成的二维码
        $filename = 'miniProgram_'.$user_id.'.png';
        //"uid=".$userid 这里就是参数，进去之后前端需要处理这个参数，可以传输用户id之类的根据 业务场景来 getUnlimit
        $response = $app->app_code->getUnlimit("uid=".$user_id, [
//            'page' => $param['page'],    //跳转的页面
//            'width' => 600,
        ]);
        // $response 成功时为 EasyWeChat\Kernel\Http\StreamResponse 实例，失败为数组或你指定的 API 返回类型
        Log::info('小程序$response::'.json_encode($response,JSON_UNESCAPED_UNICODE));

        //保存文件到本地   也可以存储在oss，根据自己业务来
        if ($response instanceof StreamedResponse) {
            $file = $response->saveAs($path,$filename);  //保存文件的操作

            $result['qrcode_url'] =  $path.$file;
            $this->success($result);
        }


    }

}
